import pandas as pd

df = pd.read_csv('static/data/info_pre.csv')


def word_cloud_data():
    tags = [j for i in df['tags'].values for j in i.split('|')]
    df_tags = pd.DataFrame(tags, columns=['tags'])
    data = [{'value': i[1], 'name': i[0]} for i in df_tags.value_counts().reset_index().head(50).values]
    return {
        'data': data
    }


def geo_data():
    region_list = ['光明区', '南山区', '宝安区', '坪山区', '盐田区', '福田区', '罗湖区', '龙华区', '龙岗区']
    data_list = df[df['region'].isin(region_list)][['title', 'region']].groupby(
        'region').count().reset_index().values.tolist()
    data = [{'value': i[1], 'name': i[0]} for i in data_list]
    return {
        'data': data
    }


def pie_data():
    dwelling_type_list = df[df['dwelling_type'] != '无']['dwelling_type'].value_counts().reset_index().values.tolist()
    data = [{'value': i[1], 'name': i[0]} for i in dwelling_type_list]
    return {
        'data': data
    }


def boxplot_data():
    region_group = df[df['price'] > 0][['region', 'price']].groupby('region')
    label = [i[0] for i in region_group]
    data = [[j[1] for j in i[1].values] for i in region_group]
    return {
        'label': label,
        'data': data
    }


def bar_data():
    df_mean = df[(df['sale_status'] != '待售') & (df['sale_status'] != '无') & (df['price'] > 0)][
        ['region', 'price', 'sale_status']]
    data = [['product', '售罄', '在售']]
    data += [
        [i] + [round(j[1])
               for j in df_mean[df_mean['region'] == i][['price', 'sale_status']].groupby('sale_status')
               .mean().reset_index().values]
        for i in df['region'].unique()
    ]
    return {
        'data': data
    }


def unit_type_bar():
    unit_type_list = [j for i in df[df['unit_type'] != '无']['unit_type'] for j in i.split('|')]
    df_unit_type = pd.DataFrame(unit_type_list, columns=['unit_type'])
    df_unit_type = df_unit_type.value_counts().reset_index()
    label = [i[0] for i in df_unit_type.values]
    data = [i[1] for i in df_unit_type.values]
    return {
        'label': label,
        'data': data
    }
